package com.tuuzed.android.sqlite.internal;

import android.support.annotation.NonNull;


public class SqlUtil {
    private SqlUtil() {
    }

    @NonNull
    public static String getCreateTableSql(@NonNull Class<?> tableClass) {
        TableInfo tableInfo = TableInfos.getTableInfo(tableClass);

        StringBuilder createSql = new StringBuilder();
        createSql.append("CREATE TABLE IF NOT EXISTS ").append(tableInfo.tableName).append('(');
        boolean first = true;
        for (ColumnInfo columnInfo : tableInfo.columnInfos) {
            if (!first) createSql.append(',');
            createSql.append(columnInfo.columnName).append(' ').append(columnInfo.columnType);
            if (columnInfo.primaryKey != null) {
                createSql.append(" PRIMARY KEY ");
                if (columnInfo.primaryKey.autoincrement()) {
                    createSql.append("AUTOINCREMENT");
                }
                createSql.append(" NOT NULL");
            } else if (columnInfo.column != null) {
                createSql.append(columnInfo.column.nullable() ? " NULL" : " NOT NULL");
            }
            first = false;
        }
        createSql.append(");\n");
        for (ColumnInfo columnInfo : tableInfo.columnInfos) {
            if (columnInfo.index == null) continue;
            createSql.append("CREATE ");
            if (columnInfo.index.unique()) {
                createSql.append(" UNIQUE INDEX ").append("unique_index_");
            } else {
                createSql.append("INDEX ").append("unique_index_");
            }
            createSql.append(tableInfo.tableName).append('_').append(columnInfo.columnName)
                    .append(" ON ").append(tableInfo.tableName).append('(').append(columnInfo.columnName);
            if (columnInfo.index.desc()) {
                createSql.append(" DESC ");
            }
            createSql.append(");\n");
        }
        return createSql.toString();
    }
}
